package com.project.frame.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.project.frame.common.cache.sys.OnLineUserCache;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 通用字段处理
 * createTime,createBy,updateTime,updateBy
 * 配合 @TableField(value="", fill=FieldFill.INSERT)
 * 或者 @TableField(value="", fill=FieldFill.UPDATE)
 * @author cjq
 * @date 2022/3/31
 */
@Component
public class CommonObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try{
            Object createTime = getFieldValByName("createTime", metaObject);
            if (createTime == null) {
                setFieldValByName("createTime", new Date(), metaObject);
            }
        }catch(Exception e){
        }
        try{
            Object createBy = getFieldValByName("createBy", metaObject);
            if (createBy == null) {
                setFieldValByName("createBy", OnLineUserCache.getInstance().getUserId(), metaObject);
            }
        }catch(Exception e){
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try{
            Object updateTime = getFieldValByName("updateTime", metaObject);
            if (updateTime == null) {
                setFieldValByName("updateTime", new Date(), metaObject);
            }
        }catch(Exception e){
        }
        try{
            Object updateBy = getFieldValByName("updateBy", metaObject);
            if (updateBy == null) {
                setFieldValByName("updateBy", OnLineUserCache.getInstance().getUserId(), metaObject);
            }
        }catch(Exception e){
        }
    }
}
